package ypmits.sound.totest {
	import flash.events.EventDispatcher;
	import flash.events.SampleDataEvent;
	import flash.media.Sound;

	/**
	 * Simple example for creating waveforms
	 * 
	 * @author Andre Michelle - http://blog.andre-michelle.com
	 */
	public class Oscillator extends EventDispatcher {

		private var _phase : Number;
		private var _sound : Sound;

		public function Oscillator() {
			_phase = 0;
			
			_sound = new Sound( );
			_sound.addEventListener( SampleDataEvent.SAMPLE_DATA, sampleDataHandler );
		}

		
		public function sampleDataHandler(event : SampleDataEvent) : void {
			var amplitude : Number;
			
			for( var i : int = 0 ; i < 2048 ; ++i ) {
				amplitude = sinus( _phase );
				
				_phase += 220 / 44100; // 220 Hz
				if( _phase > 1.0 )
					--_phase;
				
				event.data.writeFloat( amplitude ); // left
				event.data.writeFloat( amplitude ); // right
			}
		}

		
		/**
		 * returns a bipolar ~ sinus
		 */
		private function sinus( phase : Number ) : Number {
			return Math.sin( phase * 2 * Math.PI );
		}

		
		/**
		 * returns a bipolar /\ waveform
		 */
/*		private function triangle( phase : Number ) : Number {
			var t : Number = ( phase - int( phase ) ) * 4;
			if( t < 2 ) --t;
			else t = 3 - t;
			return t;
		}
*/
		
		/**
		 * returns a bipolar / sawtooth
		 */
/*		private function sawtooth( phase : Number ) : Number {
			return ( phase - int( phase ) ) * 2 - 1;
		}
*/
		
		/**
		 * returns a bipolar [ square
		 */
/*		private function square( phase : Number ) : Number {
			return ( phase - int( phase ) ) < .5 ? 1 : -1;
		}
*/
	}
}
